<template>
	<recharge title="充值后继续阅读精彩内容" unlock @payBook="payBook" @pay="pay" />
</template>

<script setup lang="ts">
	import { useUserStore } from '@/stores/user'
	import { useNovelStore } from '@/stores/novel'
	import { payBookChapter, payBookCurrency, androidpayBookCurrency, txtrack } from '@/api/index'
	import { toast } from '@/utils/index'
	import { PayBookChapterParam, PayBookCurrencyParam, gettxtrackParam } from '@/types/api'

	const novelStore = useNovelStore()
	const userStore = useUserStore()

	const novelPlugin = requirePlugin('novel-plugin')

	const payBook = async (param : PayBookChapterParam) => {
		try {
			const res = await payBookChapter(param)
			if (res == 1) {
				success()
			} else {
				toast('支付失败，请重试！')
			}
		} catch (e) {
			//TODO handle the exception
		}
	}

	const pay = async (param : PayBookCurrencyParam) => {
		try {
			const systemInfo = uni.getSystemInfoSync()
			if (systemInfo.osName === 'android') {
				const res = await androidpayBookCurrency({
					number: 1,
					...param
				})

				wx.requestVirtualPayment({
					signData: res.signData,
					paySig: res.paySig,
					signature: res.signature,
					mode: 'short_series_goods',
					success: async () => {

						success()
						const param : gettxtrackParam = {
							order_no: res.outTradeNo
						}
						const restrack = txtrack(param) || {}

						if (restrack) {
							//上报购买行为
							const app = getApp();
							app.sdk.track('PURCHASE', {

								value: res.track_money
							})

						}
					},
					fail: () => {
						toast('支付失败')
					}
				})
			} else {
				const res = await payBookCurrency({
					number: 1,
					...param
				})

				wx.requestPayment({
					timeStamp: res.timeStamp,
					nonceStr: res.nonceStr,
					package: res.package,
					signType: res.signType,
					paySign: res.paySign,
					success: async () => {

						success()
						const param : gettxtrackParam = {
							order_no: res.out_trade_no
						}
						const restrack = txtrack(param) || {}

						if (restrack) {
							//上报购买行为
							const app = getApp();
							app.sdk.track('PURCHASE', {

								value: res.track_money
							})

						}
					},
					fail: () => {
						toast('支付失败')
					}
				})
			}


		} catch (e) {
			//TODO handle the exception
		}
	}

	const success = async () => {
		toast('支付成功')
		userStore.GetUserinfo()
		// novelManagerId 句柄 用来获取novelManager实例
		const novelManager = novelPlugin.getNovelManager(novelStore.novelManagerId)
		novelManager.paymentCompleted()
		const res = await payBookChapter({
			book_id: novelStore.book_id,
			ChapterIndex: novelStore.chapterIndex
		})
		console.log('书币解锁', res)
		if (res == 1) {
			console.log('书币解锁成功', res)
			novelManager.paymentCompleted()
		}
	}
</script>